package com.jcfriends.common.manager;


import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import com.jcfriends.common.exception.session.UserSessionNotFoundException;
import com.jcfriends.main.user.pojo.UserInfo;

public class SessionManager {

	public static String USER_SESSION_NAME = "USER_SESSION";
	
	public static int getSessionUserSeq() throws Exception{
		return ((UserInfo)getUserSession()).getUserSeq();
	}
	
	/**
	 * 사용자 정보 세션을 입력(기존 사용자 세션은 삭제함)
	 * @param userSession
	 * @throws Exception
	 */
	public static void setUserSession(Object userSession) throws Exception{
		removeSession(USER_SESSION_NAME);
		setSession(USER_SESSION_NAME, userSession);
	}
	
	/**
	 * 사용자 정보 세션을 가져옴
	 * @return
	 * @throws Exception
	 */
	public static UserInfo getUserSession() throws UserSessionNotFoundException{
		try {
			UserInfo userInfo = (UserInfo)getSession(USER_SESSION_NAME);
			
			if(userInfo == null) 
				throw new NullPointerException();			
			return userInfo;
		} catch (Exception e) {
			throw new UserSessionNotFoundException();
		}
	}
	
	/**
	 * Session ID 가져오기
	 * @return
	 * @throws Exception
	 */
	public static String getSessionId() throws Exception  {
		return RequestContextHolder.getRequestAttributes().getSessionId();
	}

	/**
	 * Session 가져오기
	 * @param sessionName
	 * @return
	 * @throws Exception
	 */
	public static Object getSession(String sessionName) throws Exception {
		return (Object)RequestContextHolder.getRequestAttributes().getAttribute(sessionName, RequestAttributes.SCOPE_SESSION);
	}

	/**
	 * Session 저장
	 * @param sessionName
	 * @param sessionObject
	 * @throws Exception
	 */
	public static void setSession(String sessionName, Object sessionObject) throws Exception {
		RequestContextHolder.getRequestAttributes().setAttribute(sessionName, sessionObject, RequestAttributes.SCOPE_SESSION);
	}

	/**
	 * Session 삭제
	 * @param sessionName
	 * @throws Exception
	 */
	public static void removeSession(String sessionName) throws Exception {
		RequestContextHolder.getRequestAttributes().removeAttribute(sessionName, RequestAttributes.SCOPE_SESSION);
	}

}
